package com.zhuang.chapter12.work02;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

public class TreeMapTest {

	public static void main(String[] args) {
		TreeMap<Integer, String> treeMap = new java.util.TreeMap<Integer, String>();
		treeMap.put(1, "张三");
		treeMap.put(2, "李四");
		treeMap.put(3, "王五");
		treeMap.put(4, "小明");
		treeMap.put(5, "小李");
		SortedMap<Integer, String> sortedMap = new TreeMap<Integer, String>();
		sortedMap.put(1, "张三");
		sortedMap.put(2, "李四");
		sortedMap.put(3, "王五");
		sortedMap.put(4, "小明");
		sortedMap.put(5, "小李");

		Set<Entry<Integer, String>> entry = sortedMap.entrySet();
		/*
		 * for (Entry<Integer, String> temp : entry) { System.out.println(temp); }
		 * System.out.println("\n");
		 */
		// 这里将map.entrySet()转换成list
		List<Map.Entry<Integer, String>> list = new ArrayList<Map.Entry<Integer, String>>(entry);

		Collections.sort(list, new Comparator<Map.Entry<Integer, String>>() {
			@Override
			public int compare(Entry<Integer, String> o1, Entry<Integer, String> o2) {
				// TODO Auto-generated method stub
				return o2.getKey().compareTo(o1.getKey());
			}
		});
		// 按学号的自然顺序的倒序将这些键值对一一打印出来
		System.out.println("按学号的自然顺序的倒序将这些键值对一一打印出来");
		for (Map.Entry<Integer, String> temp : list) {
			System.out.println(temp);
		}

		// 使用map. keySet()获取键的Set集合
		System.out.println("使用map. keySet()获取键的Set集合");
		System.out.println(treeMap.keySet().toString());

		// 使用Set集合的iterator()方法获得Iterator对象用于迭代键
		System.out.println("使用Set集合的iterator()方法获得Iterator对象用于迭代键");
		Iterator<Entry<Integer, String>> iterator = treeMap.entrySet().iterator();
		while (iterator.hasNext()) {
			System.out.println(iterator.next().getKey());
		}

		// 使用Map集合的get()方法获取键所对应的值
		System.out.println("使用Map集合的get()方法获取键所对应的值");
		Set<Entry<Integer, String>> entrySet = treeMap.entrySet();
		for (Entry<Integer, String> entry2 : entrySet) {
			System.out.println(entry2.getValue());
		}
	}
}
